<template>
  <view class="login-container">
    <view class="login-box">
      <!-- 语言切换组件 -->
      <view class="lang-selector">
        <LangSelect />
      </view>

      <view class="title">{{ t('login.login') }}</view>

      <uni-forms ref="loginRef" :model="loginForm" :rules="loginRules">
        <!-- 租户选择 -->
        <uni-forms-item v-if="tenantEnabled" name="tenantId">
          <uni-data-select v-model="loginForm.tenantId" :localdata="tenantOptions" :clear="false"
            :placeholder="t('login.selectPlaceholder')" label="tenantId" label-field="text" value-field="value" />
        </uni-forms-item>

        <!-- 用户名输入 -->
        <uni-forms-item name="username">
          <uni-easyinput v-model="loginForm.username" :placeholder="t('login.username')" prefix-icon="person" />
        </uni-forms-item>

        <!-- 密码输入 -->
        <uni-forms-item name="password">
          <uni-easyinput v-model="loginForm.password" type="password" :placeholder="t('login.password')"
            prefix-icon="locked" />
        </uni-forms-item>

        <!-- 验证码 -->
        <uni-forms-item v-if="captchaEnabled" name="code">
          <view class="captcha-box">
            <uni-easyinput v-model="loginForm.code" :placeholder="$t('login.code')" prefix-icon="shield" />
            <image class="captcha-img" :src="codeUrl" mode="aspectFit" @click="getCode" />
          </view>
        </uni-forms-item>

        <!-- 登录按钮 -->
        <button class="login-btn" type="primary" @click="handleLogin" :loading="loading">
          <span v-if="!loading">{{ t('login.login') }}</span>
          <span v-else>{{ t('login.logging') }}</span>
        </button>

        <!-- 第三方登录 -->
        <view class="social-login">
          <view class="social-icons">
            <uni-icons type="weixin" size="30" @click="doSocialLogin('wechat')" />
            <uni-icons type="qq" size="30" @click="doSocialLogin('qq')" />
          </view>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import type { LoginData, TenantVO } from '@/api/types';
import { HttpStatus } from '@/enums/RespEnum';
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import LangSelect from '@/components/LangSelect/index.vue';

const userStore = useUserStore();

const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules = {
  tenantId: {
    rules: [{
      required: true,
      errorMessage: '请选择租户'
    }]
  },
  username: {
    rules: [{
      required: true,
      errorMessage: '请输入用户名'
    }]
  },
  password: {
    rules: [{
      required: true,
      errorMessage: '请输入密码'
    }]
  },
  code: {
    rules: [{
      required: true,
      errorMessage: '请输入验证码'
    }]
  }
};

const codeUrl = ref('');
const loading = ref(false);
const captchaEnabled = ref(true);
const tenantEnabled = ref(true);
const redirect = ref('/pages/index/index');
const loginRef = ref();
const tenantList = ref<TenantVO[]>([]);
const tenantOptions = ref<{ value: string; text: string }[]>([]);

const handleLogin = () => {
  loginRef.value?.validate().then(async (res: any) => {
    loading.value = true;
    if (loginForm.value.rememberMe) {
      uni.setStorageSync('tenantId', String(loginForm.value.tenantId));
      uni.setStorageSync('username', String(loginForm.value.username));
      uni.setStorageSync('password', String(loginForm.value.password));
      uni.setStorageSync('rememberMe', String(loginForm.value.rememberMe));
    } else {
      uni.removeStorageSync('tenantId');
      uni.removeStorageSync('username');
      uni.removeStorageSync('password');
      uni.removeStorageSync('rememberMe');
    }

    try {
      await userStore.login(loginForm.value);
      await userStore.getInfo();
      const redirectUrl = redirect.value || '/';
      uni.navigateTo({
        url: redirectUrl
      });
    } catch (err: any) {
      if (captchaEnabled.value) {
        getCode();
      }
      uni.showToast({
        title: err.message || '登录失败',
        icon: 'none'
      });
    } finally {
      loading.value = false;
    }
  }).catch((err: any) => {
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = uni.getStorageSync('tenantId');
  const username = uni.getStorageSync('username');
  const password = uni.getStorageSync('password');
  const rememberMe = uni.getStorageSync('rememberMe');

  // 如果有记住密码，使用存储的值，否则使用默认值
  if (rememberMe === 'true') {
    loginForm.value = {
      tenantId: tenantId || '000000',
      username: username || 'admin',
      password: password || 'admin123',
      rememberMe: true,
      code: '',
      uuid: ''
    } as LoginData;
  } else {
    // 使用默认值
    loginForm.value = {
      tenantId: '000000',
      username: 'admin',
      password: 'admin123',
      rememberMe: false,
      code: '',
      uuid: ''
    } as LoginData;
  }
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    tenantOptions.value = data.voList.map(item => ({
      value: item.tenantId,
      text: item.companyName
    }));
    if (tenantOptions.value.length > 0) {
      loginForm.value.tenantId = tenantOptions.value[0].value;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  if (!loginForm.value.tenantId) {
    uni.showToast({
      title: '1',
      icon: 'none'
    });
    return;
  }
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      window.location.href = res.data;
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      });
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});

</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
}

.lang-selector {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1;
}

.title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.captcha-box {
  display: flex;
  align-items: center;
  gap: 10px;

  .captcha-img {
    width: 120px;
    height: 40px;
    border-radius: 4px;
  }
}

.remember-box {
  margin: 15px 0;
}

.login-btn {
  width: 100%;
  margin-top: 20px;
}

.social-login {
  margin-top: 30px;
  text-align: center;

  .social-title {
    color: #666;
    margin-bottom: 15px;
  }

  .social-icons {
    display: flex;
    justify-content: center;
    gap: 20px;
  }
}
</style>
